package ua.cs.stu.ics.dbf.utils;

import org.apache.log4j.Logger;
import ua.cs.stu.ics.dbf.exceptions.DBException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 13.02.11
 * Time: 13:18
 * To change this template use File | Settings | File Templates.
 */
public class Util {
    private static Logger log = Logger.getLogger(Util.class);

    public static InputStream checkInputStream(String fileName) throws DBException {
        InputStream is = null;
        String msg;
        if (fileName == null || fileName.equals("")) {
            msg = "Unknoun filename of data base.";
            log.error(msg);
            throw new DBException(msg);
        }

        File fileBase = new File(fileName);
        if (!fileBase.exists()) {
            msg = "Data base file not found, path=" + fileName;
            log.warn(msg);

        } else {
            if (!fileBase.canRead()) {
                msg = "Can't read data from base file, path=" + fileName;
                log.error(msg);
                throw new DBException(msg);
            }
            try {
                is = new FileInputStream(fileName);
            } catch (IOException e) {
                log.error(e);
                throw new DBException("IO Error");
            }
        }
        if (is != null) log.debug("Load data from " + fileName);
        return is;
    }

    public static String convertToJavaName(String fieldName, String prefix) {
        String s = convertToJavaName(fieldName);
        if (prefix != null) {
            s = prefix + s.substring(0, 1).toUpperCase() + s.substring(1);
        }
        return s;
    }

    public static String convertToJavaName(String fieldName) {
        String buffer;
        int index;
        buffer = fieldName.toLowerCase();
        index = buffer.indexOf("_");
        while (index != -1) {
            if (index == buffer.length()-1){
                buffer = buffer.replaceAll("_", "");
                break;
            }
            Character c = buffer.charAt(index + 1);
            String arr[] = buffer.split("_" + c);
            buffer = arr[0] + c.toString().toUpperCase();
            if (arr.length > 1){
                buffer += arr[1];
                for (int i = 2; i < arr.length; i++) {
                    buffer += c.toString().toUpperCase() + arr[i];
                }
            }
            index = buffer.indexOf("_");
        }
        return buffer;

    }


}
